﻿using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

public static class LocalExt
{
    static LocalExt()
    {
        Logger = new ConsoleLogger();
        Debug = true;
    }
    public static event Action<bool> OnSet_Debug;
    public static string extInfo;

    public static bool Debug
    {
        get;
        set;
    }
    public static ILogger Logger
    {
        get;
        set;
    }
    public static void Start(int port, string hostlocalpath = null)
    {
        var server = new light.http.server.httpserver();
        server.Start(port);
        server.SetFailAction(on404);
        server.SetHttpAction("/info", onInfo);//检查信息，这一条如果查不到信息那一头就不干活
        server.SetHttpAction("/setdebug", onSetDebug);//是否调试模式
        server.SetHttpAction("/quit", onQuit);//退出程序

        LocalExt_File.WorkingPath = System.IO.Directory.GetCurrentDirectory();
        LocalExt_File.HTMLPath = hostlocalpath;
        ///文件扩展
        server.SetHttpAction("/fileext/getroots", LocalExt_File.onFileExt_GetRoots);//列出可用的根路径
        server.SetHttpAction("/fileext/dir_info", LocalExt_File.onFileExt_Dir_Info);//目录操作， 增 删 查
        server.SetHttpAction("/fileext/dir_create", LocalExt_File.onFileExt_Dir_Create);//目录操作， 增 删 查
        server.SetHttpAction("/fileext/dir_delete", LocalExt_File.onFileExt_Dir_Delete);//目录操作， 增 删 查
        server.SetHttpAction("/fileext/dir_list", LocalExt_File.onFileExt_Dir_List);//目录操作， 增 删 查
        server.SetHttpAction("/fileext/file_info", LocalExt_File.onFileExt_File_Info);//文件操作，增 删 查
        server.SetHttpAction("/fileext/file_read", LocalExt_File.onFileExt_File_Read);//文件操作，增 删 查
        server.SetHttpAction("/fileext/file_write", LocalExt_File.onFileExt_File_Write);//文件操作，增 删 查
        server.SetHttpAction("/fileext/file_delete", LocalExt_File.onFileExt_File_Delete);//文件操作，增 删 查
        server.SetHttpAction("/fileext/file_copy", LocalExt_File.onFileExt_File_Copy);//扩展，文件复制

        server.SetWebsocketAction("/ping", WSPing.WebSocketCreator);

        if (hostlocalpath != null)
        {
            server.SetHttpController("html", new light.http.server.filecontroller(hostlocalpath));
            Logger.OnLog("启动本地目录：" + hostlocalpath);
        }
    }



    public static void OpenUrl(Uri uri)
    {
        Process.Start(new ProcessStartInfo(uri.ToString()) { UseShellExecute = true });
    }
    async static Task on404(HttpContext context)
    {
        context.Response.StatusCode = 404;
        var json = new JObject();
        json["msg"] = "fail,no page.";
        json["state"] = "404";
        await context.Response.WriteAsync(json.ToString());
    }
    async static Task onInfo(HttpContext context)
    {
        context.Response.StatusCode = 200;
        var json = new JObject();
        json["tag"] = "_ttapi_localext";
        json["info"] = extInfo;
        json["state"] = "ok";
        await context.Response.WriteAsync(json.ToString());
    }
    async static Task onQuit(HttpContext context)
    {
        context.Response.StatusCode = 200;
        var json = new JObject();
        json["state"] = "ok";
        await context.Response.WriteAsync(json.ToString());
        Environment.Exit(0);
    }
    async static Task onSetDebug(HttpContext context)
    {
        var json = new JObject();
        try
        {
            var debugstr = context.Request.Query["value"].ToString().ToLower();

            if (debugstr == "true" || debugstr == "1")
            {
                Debug = true;
                if (OnSet_Debug != null) OnSet_Debug(true);
                json["state"] = "ok";
                context.Response.StatusCode = 200;

            }
            else if (debugstr == "false" || debugstr == "0")
            {
                Debug = false;
                if (OnSet_Debug != null) OnSet_Debug(false);
                json["state"] = "ok";
                context.Response.StatusCode = 200;

            }
            else
            {
                json["state"] = "error";
                json["msg"] = "fail param";
                context.Response.StatusCode = 400;
            }

            await context.Response.WriteAsync(json.ToString());
        }
        catch (Exception err)
        {
            context.Response.StatusCode = 400;
            json["msg"] = err.Message;
            json["state"] = "ok";
            await context.Response.WriteAsync(json.ToString());
            return;
        }
    }
}

